package com.led_on_off.led.slice;

import com.led_on_off.led.DeviceList;
import com.led_on_off.led.MyCommonEventSubscriber;
import com.led_on_off.led.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.bluetooth.BluetoothDeviceClass;
import ohos.bluetooth.BluetoothHost;
import ohos.bluetooth.BluetoothRemoteDevice;
import ohos.event.commonevent.CommonEventManager;
import ohos.event.commonevent.CommonEventSubscribeInfo;
import ohos.event.commonevent.CommonEventSupport;
import ohos.event.commonevent.MatchingSkills;
import ohos.rpc.RemoteException;

import java.io.IOException;
import java.net.Socket;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;

public class LedControlSlice extends AbilitySlice {
    // Button btnOn, btnOff, btnDis;
    Button On;
    Button Off;
    Button Discnt;
    Button Abt;
    String address = null;
    BluetoothHost myBluetooth = null;
    Socket socket = null;
    ToastDialog dialog = null;

    private boolean isBtConnected = false;
    //SPP UUID. Look for it
    //static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    CommonDialog commonDialog;

    private void showDialog() {
        DirectionalLayout toastLayout = (DirectionalLayout) LayoutScatter.getInstance(this)
                .parse(ResourceTable.Layout_dialog_myself, null, false);
        commonDialog = new CommonDialog(getContext());
        commonDialog.setContentCustomComponent(toastLayout).show();
    }

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_led_control);

        subscribe();

        address = intent.getStringParam(DeviceList.EXTRA_ADDRESS);

        myBluetooth =  BluetoothHost.getDefaultHost(this);

        On = (Button) findComponentById(ResourceTable.Id_on_btn);
        Off = (Button) findComponentById(ResourceTable.Id_off_btn);
        Discnt = (Button) findComponentById(ResourceTable.Id_dis_btn);
        Abt = (Button) findComponentById(ResourceTable.Id_abt_btn);

        ConnectBT(getContext());

        On.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                turnOnLed();
            }
        });

        Off.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                turnOffLed();
            }
        });

        Discnt.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                Disconnect();   //close connection
            }
        });
    }

    public void subscribe(){
        String event = "com.led_on_off.led";
        MatchingSkills matchingSkills = new MatchingSkills();
        matchingSkills.addEvent(event); // 自定义事件
        matchingSkills.addEvent(CommonEventSupport.COMMON_EVENT_BLUETOOTH_HOST_DISCOVERY_STARTED);
        matchingSkills.addEvent(CommonEventSupport.COMMON_EVENT_BLUETOOTH_HOST_DISCOVERY_FINISHED);
        CommonEventSubscribeInfo subscribeInfo = new CommonEventSubscribeInfo(matchingSkills);
        MyCommonEventSubscriber subscriber = new MyCommonEventSubscriber(subscribeInfo);
        try {
            CommonEventManager.subscribeCommonEvent(subscriber);
        } catch (RemoteException e) {
            //HiLog.error(LABEL, "Exception occurred during subscribeCommonEvent invocation.");
        }
    }



    private void Disconnect() {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                msg("Error");
            }
        }
    }

    private void turnOnLed() {
        if (socket != null) {
            try {
                socket.getOutputStream().write("1".toString().getBytes());
            } catch (IOException e) {
                msg("Error");
            }
        }
    }

    private void turnOffLed() {
        if (socket != null) {
            try {
                socket.getOutputStream().write("0".toString().getBytes());
            } catch (IOException e) {
                msg("Error");
            }
        }
    }

    public void about(Component component) {
        if (component.getId() == ResourceTable.Id_abt_btn) {
            Intent intent = new Intent();
            Operation operation = new Intent.OperationBuilder()
                    .withDeviceId("")
                    .withBundleName("com.led_on_off.led")
                    .withAbilityName("com.led_on_off.led.AboutAbility")
                    .build();
            intent.setOperation(operation);
            startAbility(intent);
        }
    }

    public void ConnectBT(Context context) {
        showDialog();
        boolean ConnectSuccess = true; //if it's here, it's almost connected
        context.createSerialTaskDispatcher("", TaskPriority.DEFAULT).asyncDispatch(new Runnable() {
            @Override
            public void run() {
                if (socket == null || !isBtConnected) {
                    myBluetooth.enableBt();
                    myBluetooth.startBtDiscovery();
                    BluetoothRemoteDevice disPosition = myBluetooth.getRemoteDev(address);
                    disPosition.startPair();
                }
                context.getUITaskDispatcher().asyncDispatch(new Runnable() {

                    @Override
                    public void run() {
                        if (!ConnectSuccess) {
                            msg("Connection Failed. Is it a SPP Bluetooth? Try again.");
                            terminate();
                        } else {
                            msg("Connected.");
                            isBtConnected = true;
                        }
                        commonDialog.destroy();
                    }
                });
            }
        });
    }

    private void msg(String s) {
        dialog.setText(s).show();
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
